﻿using KingerRobot.MexicoSailunWMS.Spi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KingerRobot.MexicoSailunWMS.SpiService;

internal class BLogInfoManager : ILogInfoManager
{
    public List<OperationLogBeans> QueryOperationLog()
    {
        var db = Db.Default;
        var query = db.LogOperations.Select(f => new OperationLogBeans
        {
            Id = f.Id,
            OperationName = f.OperationName,
            ClientIP = f.Clientip,
            InParams = f.InParams,
            OutParams = f.OutParams,
            UserName = f.UserName,
            CreateTime = f.CreateTime,
            UpdateTime = f.UpdateTime,
            OperationStatus = f.OperationStatus,
            Remark = f.Remark
        }).OrderByDescending(f => f.CreateTime).ToList();
        return query;
    }

    public List<CrnLogBeans> QueryCrnLog(CrnLogParam param)
    {
        if (param is null) return new();
        var dbHelper = new DbHelper();
        var sql = new StringBuilder();
        sql.Append(@$"SELECT TaskNo,CrnName,CmdType,TaskStatus,ProductCode,LocName,
		            Spec,MaterialName,CreateTime,RemarkMemo
	                    FROM (SELECT bwt.task_no TaskNo ,
			            rectf.crn_equip_name CrnName ,
			            bwtc.cmd_type  CmdType ,
			            bwt.task_status TaskStatus,
			            pp.product_code ProductCode,
			            rl.loc_name  LocName,
			            pm.spec Spec,
			            pm.material_name  MaterialName,
			            bwt.create_time  CreateTime ,
			            bwt.remark_memo  RemarkMemo 
		            FROM bak_wcs_task bwt 
		            inner join bak_wcs_task_cmd bwtc on bwt.objid  = bwtc.task_id AND bwtc.equip_id in (select objid from rcs_equip re WHERE re.equip_type = 4)
		            LEFT JOIN prod_sku_product psp on bwt.sku_id = psp.sku_id 
		            LEFT JOIN prod_product pp on psp.product_id = pp.objid 
		            LEFT JOIN prod_material pm on pp.material_id = pm.objid 
		            LEFT JOIN rcs_location rl on bwt.target_loc  = rl.objid 
		            LEFT JOIN rcs_equip_crn_to_fork rectf  on bwtc.equip_id = rectf.folk_equip_id 
            )tab
        WHERE 1 = 1");

        if (param.TaskNo is not null && param.TaskNo > 0) sql.Append($"AND TaskNo = {param.TaskNo} ");//指定任务号
        if (!string.IsNullOrWhiteSpace(param.CrnName)) sql.Append($"AND  CrnName = '{param.CrnName}' ");//指定堆垛机
        if (param.CmdType is not null && param.CmdType > 0) sql.Append($"AND CmdType = {param.CmdType} ");//指定任务类型
        if (param.TaskStatus is not null && param.TaskStatus > 0) sql.Append($"AND TaskStatus = {param.TaskStatus} ");//指定任务状态
        if (!string.IsNullOrWhiteSpace(param.ProductCode)) sql.Append($"AND ProductCode = '{param.ProductCode}' ");//指定条码
        if (!string.IsNullOrWhiteSpace(param.LocName)) sql.Append($"AND LocName = '{param.LocName}' ");//指定目标位
        if (!string.IsNullOrWhiteSpace(param.Spec)) sql.Append($"AND Spec = '{param.Spec}' ");//指定spec码
        if (!string.IsNullOrWhiteSpace(param.MaterialName)) sql.Append($"AND MaterialName = '{param.MaterialName} '");//指定物料名
        if (param.StartTime is not null && param.StartTime > DateTime.MinValue)
        {//指定开始时间 
            var startTime = ((DateTime)param.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
            sql.Append($"AND CreateTime > '{startTime}' ");
        }
        if (param.EndTime is not null && param.EndTime > DateTime.MinValue)
        {//指定结束时间
            var endTime = ((DateTime)param.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
            sql.Append($"AND CreateTime < '{endTime}' ");
        }
        sql.Append($" ORDER by CreateTime desc;");

        dbHelper.CommandText = sql.ToString();
        dbHelper.CommandType = System.Data.CommandType.Text;
        var result = dbHelper.GetXDataTable();
        if (result == null || result.DataTable == null || result.DataTable.Rows == null || result.DataTable.Rows.Count == 0) return new();

        List<CrnLogBeans> list = new List<CrnLogBeans>();


        for (int i = 0; i < result.DataTable.Rows.Count; i++)
        {
            var entity = result.DataTable.Rows[i].Map<CrnLogBeans>();
            list.Add(entity);
        }
        return list;
    }

    public List<EMSLogBeans> QueryEMSLog(EMSLogParam param)
    {
        if (param is null) return new();
        var dbHelper = new DbHelper();
        var sql = new StringBuilder();
        sql.Append(@$"SELECT TaskNo,ProductCode,EmsName,CuringCode,TargetLoc,CmdType,TaskStatus,
		                    MaterialName,Spec,CreateTime,RemarkMemo
	                    FROM 		
		                    (SELECT 
			                    bwt.task_no TaskNo,
			                    pp.product_code ProductCode,
			                    re2.equip_name EmsName,
			                    rl.loc_code CuringCode,
			                    rl.loc_name TargetLoc,
			                    bwtc.cmd_type CmdType,
			                    bwtc.cmd_status TaskStatus,
			                    pm.material_name MaterialName,
			                    pm.spec Spec,
			                    bwt.create_time CreateTime,
			                    bwt.remark_memo RemarkMemo
			                    FROM bak_wcs_task bwt 
			                    inner join bak_wcs_task_cmd bwtc on bwt .objid = bwtc.task_id AND bwtc.equip_id in (select objid  FROM  rcs_equip re WHERE equip_type = 10)
			                    LEFT  join rcs_equip re2 on re2.objid = bwtc.equip_id 
			                    LEFT JOIN rcs_location rl on bwt.target_loc = rl.objid  
			                    LEFT JOIN prod_sku_product psp on psp.sku_id = bwt.sku_id 
			                    LEFT JOIN prod_product pp on psp.product_id  = pp.objid 
			                    LEFT JOIN prod_material pm on pp.material_id = pm.objid) tab
	                     WHERE 1 = 1");

        if (param.TaskNo is not null && param.TaskNo > 0) sql.Append($"AND TaskNo = {param.TaskNo} ");//指定任务号
        if (!string.IsNullOrWhiteSpace(param.EmsName)) sql.Append($"AND  EmsName = '{param.EmsName}' ");//指定EMS
        if (!string.IsNullOrWhiteSpace(param.CuringCode)) sql.Append($"AND  CuringCode = '{param.CuringCode}' ");//指定硫化机编号
        if (param.CmdType is not null && param.CmdType > 0) sql.Append($"AND CmdType = {param.CmdType} ");//指定任务类型
        if (param.TaskStatus is not null && param.TaskStatus > 0) sql.Append($"AND TaskStatus = {param.TaskStatus} ");//指定任务状态
        if (!string.IsNullOrWhiteSpace(param.ProductCode)) sql.Append($"AND ProductCode = '{param.ProductCode}' ");//指定条码
        if (!string.IsNullOrWhiteSpace(param.TargetLoc)) sql.Append($"AND TargetLoc = '{param.TargetLoc} '");//指定目标位
        if (!string.IsNullOrWhiteSpace(param.Spec)) sql.Append($"AND Spec = '{param.Spec} '");//指定spec码
        if (!string.IsNullOrWhiteSpace(param.MaterialName)) sql.Append($"AND MaterialName = '{param.MaterialName}' ");//指定物料名
        if (param.StartTime is not null && param.StartTime > DateTime.MinValue)
        {//指定开始时间 
            var startTime = ((DateTime)param.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
            sql.Append($"AND CreateTime > '{startTime}' ");
        }
        if (param.EndTime is not null && param.EndTime > DateTime.MinValue)
        {//指定结束时间
            var endTime = ((DateTime)param.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
            sql.Append($"AND CreateTime < '{endTime}' ");
        }
        sql.Append($" ORDER by CreateTime desc;");

        dbHelper.CommandText = sql.ToString();
        dbHelper.CommandType = System.Data.CommandType.Text;
        var result = dbHelper.GetXDataTable();
        if (result is null || result.DataTable is null || result.DataTable.Rows is null || result.DataTable.Rows.Count <= 0) return new();
        List<EMSLogBeans> list = new List<EMSLogBeans>();
        for (int i = 0; i < result.DataTable.Rows.Count; i++)
        {
            var entity = result.DataTable.Rows[i].Map<EMSLogBeans>();
            list.Add(entity);
        }
        return list;
    }

    public List<ScannerLogBeans> QueryScannerLog(ScannerLogParam param)
    {
        var dbHelper = new DbHelper();
        var sql = new StringBuilder();
        sql.Append(@$"SELECT TaskNo,ProductCode,ScannerName,CmdType,TaskStatus,
		                    Spec,MaterialName,CreateTime,RemarkMemo
	                    FROM 		
		                    (SELECT 
			                    bwt.task_no TaskNo,
			                    pp.product_code ProductCode,
			                    re2.equip_name ScannerName,
			                    bwtc.cmd_type CmdType,
			                    bwtc.cmd_status TaskStatus,
			                    pm.material_name MaterialName,
			                    pm.spec Spec,
			                    bwt.create_time CreateTime,
			                    bwt.remark_memo RemarkMemo
			                    FROM bak_wcs_task bwt 
			                    inner join bak_wcs_task_cmd bwtc on bwt .objid = bwtc.task_id AND bwtc.equip_id in (select objid  FROM  rcs_equip re WHERE equip_type = 8)
			                    LEFT  join rcs_equip re2 on re2.objid = bwtc.equip_id 
			                    LEFT JOIN prod_sku_product psp on psp.sku_id = bwt.sku_id 
			                    LEFT JOIN prod_product pp on psp.product_id  = pp.objid 
			                    LEFT JOIN prod_material pm on pp.material_id = pm.objid) tab
	                     WHERE 1 = 1");

        if (param.TaskNo is not null && param.TaskNo > 0) sql.Append($"AND TaskNo = {param.TaskNo} ");//指定任务号
        if (!string.IsNullOrWhiteSpace(param.ScannerName)) sql.Append($"AND  ScannerName = '{param.ScannerName}' ");//指定扫描仪
        if (param.CmdType is not null && param.CmdType > 0) sql.Append($"AND CmdType = {param.CmdType} ");//指定任务类型
        if (param.TaskStatus is not null && param.TaskStatus > 0) sql.Append($"AND TaskStatus = {param.TaskStatus} ");//指定任务状态
        if (!string.IsNullOrWhiteSpace(param.ProductCode)) sql.Append($"AND ProductCode = '{param.ProductCode}' ");//指定条码
        if (!string.IsNullOrWhiteSpace(param.Spec)) sql.Append($"AND Spec = '{param.Spec} '");//指定spec码
        if (!string.IsNullOrWhiteSpace(param.MaterialName)) sql.Append($"AND MaterialName = '{param.MaterialName}' ");//指定物料名
        if (param.StartTime is not null && param.StartTime > DateTime.MinValue)
        {//指定开始时间 
            var startTime = ((DateTime)param.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
            sql.Append($"AND CreateTime > '{startTime}' ");
        }
        if (param.EndTime is not null && param.EndTime > DateTime.MinValue)
        {//指定结束时间
            var endTime = ((DateTime)param.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
            sql.Append($"AND CreateTime < '{endTime}' ");
        }
        sql.Append($" ORDER by CreateTime desc;");

        dbHelper.CommandText = sql.ToString();
        dbHelper.CommandType = System.Data.CommandType.Text;
        var result = dbHelper.GetXDataTable();
        if (result is null || result.DataTable is null || result.DataTable.Rows is null || result.DataTable.Rows.Count <= 0) return new();
        List<ScannerLogBeans> list = new List<ScannerLogBeans>();
        for (int i = 0; i < result.DataTable.Rows.Count; i++)
        {
            var entity = result.DataTable.Rows[i].Map<ScannerLogBeans>();
            list.Add(entity);
        }

        return list;
    }

    public List<TireTurnBeans> QueryTireTurnLog(TireTurnParam param)
    {
        var dbHelper = new DbHelper();
        var sql = new StringBuilder();
        sql.Append($@"SELECT TaskNo,ProductCode,CuringCode,TargetName,CreateTime,RemarkMemo
	                    FROM 		
		                    (SELECT 
			                    bwt.task_no TaskNo,
			                    bwt.task_type TaskType,
			                    pp.product_code ProductCode,
			                    rl.loc_code  CuringCode,
			                    rl.loc_name TargetName,
			                    rl.objid LocId,
			                    bwt.create_time CreateTime,
			                    bwt.remark_memo RemarkMemo
			                    FROM bak_wcs_task bwt 
			                    inner  join rcs_location rl on bwt.target_loc = rl.objid  AND bwt.target_loc in (SELECT objid  FROM rcs_location rl WHERE rl.loc_type in (0,7))
			                    LEFT JOIN prod_sku_product psp on psp.sku_id = bwt.sku_id 
			                    LEFT JOIN prod_product pp on psp.product_id  = pp.objid 
			                    LEFT JOIN prod_material pm on pp.material_id = pm.objid AND pm.PCSPCRBarcodePosition = 'Down') tab
	                     WHERE 1 = 1");

        if (param.TaskNo is not null && param.TaskNo > 0) sql.Append($"AND TaskNo = {param.TaskNo} ");//指定任务号
        if (!string.IsNullOrWhiteSpace(param.CuringCode)) sql.Append($"AND  CuringCode = '{param.CuringCode}' ");//指定硫化机
        if (!string.IsNullOrWhiteSpace(param.ProductCode)) sql.Append($"AND ProductCode = '{param.ProductCode}' ");//指定条码
        if (!string.IsNullOrWhiteSpace(param.TargetName)) sql.Append($"AND TargetName = '{param.TargetName} '");//指定目标位
        if (param.StartTime is not null && param.StartTime > DateTime.MinValue)
        {//指定开始时间 
            var startTime = ((DateTime)param.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
            sql.Append($"AND CreateTime > '{startTime}' ");
        }
        if (param.EndTime is not null && param.EndTime > DateTime.MinValue)
        {//指定结束时间
            var endTime = ((DateTime)param.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
            sql.Append($"AND CreateTime < '{endTime}' ");
        }

        sql.Append($" ORDER by CreateTime desc;");


        dbHelper.CommandText = sql.ToString();
        dbHelper.CommandType = System.Data.CommandType.Text;
        var result = dbHelper.GetXDataTable();
        if (result is null || result.DataTable is null || result.DataTable.Rows is null || result.DataTable.Rows.Count <= 0) return new();

        List<TireTurnBeans> list = new List<TireTurnBeans>();
        for (int i = 0; i < result.DataTable.Rows.Count; i++)
        {
            var entity = result.DataTable.Rows[i].Map<TireTurnBeans>();
            entity.IsNeedTurn = "是";
            list.Add(entity);
        }
        return list;
    }





    public string GetTaskType(int? taskType)
    {
        if (taskType is not null && taskType > 0)
        {
            switch (taskType)
            {
                case (int)EnumTaskType.Abnormal:
                    return "异常任务";
                    break;
                case (int)EnumTaskType.EMS:
                    return "EMS任务";
                    break;
                case (int)EnumTaskType.Exwarehouse:
                    return "出库任务";
                    break;
                case (int)EnumTaskType.Rotate:
                    return "旋转任务";
                    break;
                case (int)EnumTaskType.Transportation:
                    return "输送任务";
                    break;
                case (int)EnumTaskType.Warehousing:
                    return "入库任务";
                    break;
                default:
                    return "";
            }
        }
        else return "";
    }



    public string GetTaskStatus(int? taskStatus)
    {
        if (taskStatus is not null && taskStatus > 0)
        {
            switch (taskStatus)
            {
                case (int)EnumTaskStatus.Create:
                    return "创建";
                    break;
                case (int)EnumTaskStatus.Executable:
                    return "可执行";
                    break;
                case (int)EnumTaskStatus.Executed:
                    return "已执行";
                    break;
                case (int)EnumTaskStatus.Finish:
                    return "任务完成";
                    break;
                default:
                    return "";
            }
        }
        else return "";
    }





}
